有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Java中打印三角形?

我是Java的初学者。我用Deitel和Deitel学习Java,练习中的一个问题要求你打印三角形。问题是:

(Triangle Printing Program) Write an application that displays the following patterns separately, one below the other. Use for loops to generate the patterns. All asterisks (*) should be printed by a single statement of the form System.out.print( '*' ); which causes the asterisks to print side by side. A statement of the form System.out.println(); can be used to move to the next line. A statement of the form System.out.print( ' ' );` can be used to display a space for the last two patterns. There should be no other output statements in the program.

(a)   (b)        (c)   (d)
* ********** ********** *
** ********* ********* **
*** ******** ******** ***
**** ******* ******* ****
***** ****** ****** *****
****** ***** ***** ******
******* **** **** *******
******** *** *** ********
********* ** ** *********
********** * * **********

我得到了a,但我需要一些b、c和d方面的帮助。提前谢谢!:)

另外,这是我的a代码:

public class p5_15
{
    public static void main( String[] args )
    {

        int line;
        int star;

        for( line = 1; line <= 10; line++ )
        {
            for( star = 1; star <= line; star++ )
            {
                System.out.print( "*" );
            }
            System.out.println();
        }
    }
} 

共 (1) 个答案

  1. # 1 楼答案

    您需要使用嵌套在另一个for循环中的for循环。语法如下所示:

    for(int i = 0; i < n; ++i)
        for(int j = 0; j < i; ++j)
           ...
    

    根据要绘制的三角形,需要使用...替换的表达式以及第二个for循环的初始化和条件

    例如,在(c)中,在第一行(i=0)上,您希望j从0开始并递增到9(即您打印的星星数-1)。然后下一行(i=1),你希望j从0开始,递增到8。你应该已经注意到了一种模式